package com.example.exampletest.controller;

import com.example.exampletest.model.Course;
import com.example.exampletest.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import jakarta.servlet.http.HttpSession;

@Controller
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;

    // 课程列表+搜索
    @GetMapping("/list")
    public String list(@RequestParam(value = "keyword", required = false) String keyword,
                      @RequestParam(value = "sortOrder", required = false) Integer sortOrder,
                      Model model) {
        List<Course> courses = courseService.searchCourses(keyword, sortOrder);
        model.addAttribute("courses", courses);
        return "course/list";
    }

    // 课程详情
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Long id, @RequestParam(value = "from", required = false) String from, Model model) {
        Course course = courseService.getCourseById(id);
        model.addAttribute("course", course);
        model.addAttribute("from", from);
        return "course/detail";
    }

    // 课程添加页面
    @GetMapping("/add")
    public String addPage() {
        return "course/add";
    }

    // 课程添加
    @PostMapping("/add")
    public String add(Course course,
                     @RequestParam(value = "coverFile", required = false) MultipartFile coverFile,
                     @RequestParam(value = "videoFile", required = false) MultipartFile videoFile,
                     HttpSession session) {
        Integer enterpriseId = (Integer) session.getAttribute("enterpriseId");
        course.setEnterpriseId(enterpriseId);
        course.setStatus(0); // 草稿
        // 处理封面文件
        if (coverFile != null && !coverFile.isEmpty()) {
            String coverUrl = saveFile(coverFile, "uploads");
            course.setCoverUrl(coverUrl);
        }
        // 处理视频文件
        if (videoFile != null && !videoFile.isEmpty()) {
            String videoUrl = saveFile(videoFile, "uploads");
            course.setVideoUrl(videoUrl);
        }
        courseService.addCourse(course);
        return "redirect:/course/list";
    }

    // 文件保存工具方法
    private String saveFile(MultipartFile file, String dir) {
        // 保存到项目根目录下的uploads目录
        String uploadDir = System.getProperty("user.dir") + File.separator + dir;
        File uploadPath = new File(uploadDir);
        if (!uploadPath.exists()) uploadPath.mkdirs();
        String ext = StringUtils.getFilenameExtension(file.getOriginalFilename());
        String filename = UUID.randomUUID().toString() + (ext != null ? ("." + ext) : "");
        File dest = new File(uploadPath, filename);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
        return "/uploads/" + filename;
    }

    // 课程编辑页面
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        Course course = courseService.getCourseById(id);
        model.addAttribute("course", course);
        return "course/edit";
    }

    // 课程编辑
    @PostMapping("/edit")
    public String edit(Course course) {
        courseService.updateCourse(course);
        return "redirect:/course/list";
    }

    // 课程删除
    @PostMapping("/delete/{id}")
    public String delete(@PathVariable Long id) {
        courseService.deleteCourse(id);
        return "redirect:/course/list";
    }

    // 提交审核
    @PostMapping("/submitAudit/{id}")
    public String submitAudit(@PathVariable Long id) {
        courseService.updateCourseStatus(id, 1, null); // 1=待审核
        return "redirect:/course/list";
    }

    // 审核列表（超级管理员）
    @GetMapping("/audit/list")
    public String auditList(Model model) {
        List<Course> courses = courseService.getCoursesByStatus(1); // 1=待审核
        model.addAttribute("courses", courses);
        return "course/audit_list";
    }

    // 审核通过
    @PostMapping("/audit/approve/{id}")
    public String approve(@PathVariable Long id) {
        courseService.updateCourseStatus(id, 2, null); // 2=审核通过
        return "redirect:/course/audit/list";
    }

    // 审核不通过
    @PostMapping("/audit/reject/{id}")
    public String reject(@PathVariable Long id, @RequestParam String reason) {
        courseService.updateCourseStatus(id, 3, reason); // 3=审核不通过
        return "redirect:/course/audit/list";
    }
} 